package com.jic.market.impl.rest.discount.processor;

import com.jic.market.common.util.Money;
import com.jic.market.entity.PromotionLimitRuleEntity;
import com.jic.market.entity.PromotionMemberGrade;
import com.jic.market.entity.PromotionRuleEntity;
import com.jic.market.enums.FrontPromotionTypeEnum;
import com.jic.market.impl.rest.discount.model.GoodsDetailModel;
import com.jic.market.mapper.DiscountProductSingleDetailMapper;
import com.jic.market.service.PromotionMemberGradeService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author yinhaijun
 * @date: 2020/5/7
 */
public class BaseDiscountProcessor {

    @Autowired
    private DiscountProductSingleDetailMapper discountProductSingleDetailMapper;
    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    protected Boolean checkPromotion(String thirdUserId, String channelCode, String channelCodes, List<PromotionMemberGrade> promotionMemberGradeList){
        return promotionMemberGradeService.checkPromotion(thirdUserId, channelCode, channelCodes, promotionMemberGradeList);
    }


    protected LimitRuleResult checkCommonLimitRule(PromotionLimitRuleEntity promotionLimitRuleEntity, String promotionId, GoodsDetailModel goodsDetailModel, FrontPromotionTypeEnum frontPromotionTypeEnum, String thirdUserId){
        String thirdSkuId = goodsDetailModel.getThirdSkuId();
        Long num = goodsDetailModel.getNum().longValue();
        if(frontPromotionTypeEnum == FrontPromotionTypeEnum.XOFFER_DI_X_Y_ZE
            || frontPromotionTypeEnum == FrontPromotionTypeEnum.XOFFER_DI_X_Y_YUAN){
            num = 1L;
        }
        LimitRuleResult limitRuleResult = new LimitRuleResult();
        boolean isSinglePromotion = promotionId.equals(goodsDetailModel.getPromotionId());//相等时说明是单品类促销
        boolean checkChannelStoreLimit = true;
        boolean checkChannelIndividualLimit = true;
        Long channelStoreValidNum = num;//单渠道门店有效数量
        Long channelIndividualValidNum = num; //单渠道个人有效数量
//        PromotionLimitRuleEntity promotionLimitRuleEntity = promotionLimitRuleEntityMapper.getEntityByPromotionIdAndMpId(Long.parseLong(promotionId), skuId);
        if(null != promotionLimitRuleEntity){
            // 单渠道门店限制
            Long channelStoreLimit = promotionLimitRuleEntity.getChannelStoreLimit();
            Integer countNum;
            if(isSinglePromotion){
                countNum = discountProductSingleDetailMapper.countSingleValidNumNumByPromotionIdAndThirdSkuId(promotionId, thirdSkuId);
            }else {
                countNum = discountProductSingleDetailMapper.countConditionValidNumNumByPromotionIdAndThirdSkuId(promotionId, thirdSkuId);
            }
            if(null == countNum){
                countNum = 0;
            }
            if(null != channelStoreLimit && null != channelStoreLimit && null != countNum){
                checkChannelStoreLimit = channelStoreLimit >= countNum + num;
                if(!checkChannelStoreLimit){
                    channelStoreValidNum = channelStoreLimit - countNum <= 0L ? 0L : channelStoreLimit - countNum;
                }
            }
            // 单渠道个人限制
            Long channelIndividualLimit = promotionLimitRuleEntity.getChannelIndividualLimit();
            Integer userCountNum;
            if(isSinglePromotion){
                userCountNum = discountProductSingleDetailMapper.countSingleValidNumByPromotionIdAndThirdSkuIdAndThirdUserId(promotionId, thirdSkuId, thirdUserId);
            }else {
                userCountNum = discountProductSingleDetailMapper.countConditionValidNumByPromotionIdAndThirdSkuIdAndThirdUserId(promotionId, thirdSkuId, thirdUserId);
            }
            if(null == userCountNum){
                userCountNum = 0;
            }
            if(null != channelIndividualLimit && null != channelIndividualLimit && null != userCountNum){
                checkChannelIndividualLimit = channelIndividualLimit >= userCountNum + num;
                if(!checkChannelIndividualLimit){
                    channelIndividualValidNum = channelIndividualLimit - userCountNum <= 0L ? 0L : channelIndividualLimit - userCountNum;
                }
            }
        }
        Long validNum = channelStoreValidNum < channelIndividualValidNum ? channelStoreValidNum : channelIndividualValidNum;
        limitRuleResult.setValidNum(validNum);
        limitRuleResult.setLimitCheck(limitRuleResult.getValidNum() > 0);
        if(isSinglePromotion){
            goodsDetailModel.setSingleValidNum(validNum);
        }else {
            goodsDetailModel.setConditionValidNum(validNum);
        }
        return limitRuleResult;
    }




    // type是返回类型1金额，2折扣,3数量
    protected BigDecimal getFlightContentValue(Boolean overlayAppFlag, Integer overlayAppNum, BigDecimal condition, List<PromotionRuleEntity> promotionRuleEntityList, Integer type) {
        if(null == overlayAppFlag){
            return BigDecimal.ZERO;
        }
        if(null != promotionRuleEntityList && !promotionRuleEntityList.isEmpty()){
            // 超量，按匹配最高层级享受优惠
            if(!overlayAppFlag){
                BigDecimal newContentValue = null;
                Integer level = null;
                for(int i = 0; i<promotionRuleEntityList.size();i++){
                    BigDecimal newConditionValueResult = pipei(promotionRuleEntityList.get(i), condition, 1, type);
                    if(i==0){
                        newContentValue = newConditionValueResult;
                        level = promotionRuleEntityList.get(i).getLevel();
                    }else if(promotionRuleEntityList.get(i).getLevel() > level && null != newConditionValueResult){
                        newContentValue = newConditionValueResult;
                        level = promotionRuleEntityList.get(i).getLevel();
                    }
                }
                return newContentValue;
            }
            // 倍量，取第一条，然后按上限次数进行设置，比如满200送10元，上限为3，那么我买1000元的东西应该送30元
            // 如果是折扣，则不变
            else {
                PromotionRuleEntity promotionRuleEntity = promotionRuleEntityList.get(0);
                BigDecimal newContentValue = pipei(promotionRuleEntity, condition, overlayAppNum, type);
                return newContentValue;
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * @param promotionRuleEntity
     * @param condition
     * @param maxMult
     * @param type 1金额，2折扣,3数量
     * @return
     */
    private BigDecimal pipei(PromotionRuleEntity promotionRuleEntity, BigDecimal condition, Integer maxMult, Integer type){
        if(condition == null || maxMult == null || condition.compareTo(BigDecimal.ZERO) == 0 || maxMult.equals(0)){
            return null;
        }
        Long conditionValue = promotionRuleEntity.getConditionValue();

        BigDecimal contentValue = promotionRuleEntity.getContentValue();

        if(conditionValue == null || contentValue == null || conditionValue.equals(0) || contentValue.equals(0)){
            return null;
        }
        BigDecimal divideInt = bijiao(promotionRuleEntity, condition);
        if(null == divideInt || divideInt.compareTo(BigDecimal.ZERO) == 0){
            return null;
        }
        if(divideInt.compareTo(new BigDecimal(maxMult)) == 1){
            divideInt = new BigDecimal(maxMult);
        }
        if(type.equals(1)){
            return Money.multiply(Money.divide(contentValue, new BigDecimal(100)), divideInt);
        }
        if(type.equals(2)){
            return Money.multiply(Money.divide(contentValue, new BigDecimal(10)), divideInt);
        }
        if(type.equals(3)){
            return contentValue;
        }
        return null;
    }
    private BigDecimal bijiao(PromotionRuleEntity promotionRuleEntity, BigDecimal condition){
        BigDecimal conditionValue = null;
        if(promotionRuleEntity.getConditionType().equals(1)){
            conditionValue = Money.divide(new BigDecimal(promotionRuleEntity.getConditionValue()), new BigDecimal(100));
        }
        if(promotionRuleEntity.getConditionType().equals(2)){
            conditionValue= new BigDecimal(promotionRuleEntity.getConditionValue());
        }
        if(condition.compareTo(conditionValue) == -1){
            return BigDecimal.ZERO;
        }else{
            return Money.divideInt(condition, conditionValue);
        }
    }
    @Data
    public static class LimitRuleResult{
        private Boolean limitCheck; //通过校验
        private Long validNum; //有效数量
    }

}
